package com.thinkcar.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.thinkcar.core.exception.Result;
import com.thinkcar.gateway.enums.ExceptionEnum;
import jakarta.annotation.PostConstruct;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;

@Configuration
public class SentinelConfig {

    @PostConstruct
    public void initSentinelBlockHandler() {
        // 明确实现 BlockRequestHandler 接口
        BlockRequestHandler blockRequestHandler = (exchange, throwable) ->
                ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromValue(Result.failed(ExceptionEnum.FLOW.getCode(), ExceptionEnum.FLOW.getMsg())));

        // 注册到全局回调管理器
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }
}
